import { createRouter, createWebHashHistory } from "vue-router";
import { getToken } from "../utils/auth.js";
import {clearLoginInfo} from '../utils/index.js'
import {apiRoutes} from './apiRouter.js'
import _import from './_import.js'

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  { path: '/404', component: _import('common/404'), name: '404', hidden: true, meta: { title: '404未找到' } },
  { path: '/login', component: _import('common/login'), name: 'login', meta: { title: '登录' }},
]
// 自定义菜单
const customRoute = [
    { path: '/productPreview', component: _import('productCenter/productPreview'), name: 'productPreview', hidden: true, meta: { title: '预览产品' }}
]
// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/',
  component: _import('main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口整体布局' },
  children: [
    { path: '/home', component: _import('common/home'), name: 'home', hidden: true, meta: { title: '首页' }},
    ...customRoute,
  ],
  beforeEnter(to, from, next) {
    const token = getToken();
    if (!token || !/\S/.test(token)) {
      clearLoginInfo()
      next({ name: 'login' })
    }
    next()
  }
}
const router = createRouter({
  history: createWebHashHistory(),
  scrollBehavior: () => ({ y: 0 }), // 对于所有路由导航，简单的让页面滚动到顶部
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes),
});
// 路由监听
router.beforeEach(async(to, from, next) => {
  const token = getToken();
  if (token) {
    if(router.options.isAddDynamicMenuRoutes){
      next()
    }else{
      await getApiRouter()
      router.options.isAddDynamicMenuRoutes = true
      console.log(router.getRoutes());
      next({path: `${to.path}`})
    }
  } else {
    if (to.name !== "login"&&!to.meta.notLogin) next({name: 'login'});
    else next()
  }
});
// 动态添加路由
const getApiRouter = async() => {
  let subList = await apiRoutes() // 
  let newList = [ {
    path: "/404",
    name: "NotFound",
    component: _import('common/404')
  },
  {
    path: "/:pathMatch(.*)",
    redirect: "/404"
  }]
  subList.forEach((r) => {router.addRoute('main',r)})
  newList.forEach((r) => {router.addRoute(r)})
}

export default router;